// pages/we/mail/mail.js
import utils from '../../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    score: {},
    modalName: '',
    gift: '',
    price: 0,
    files: [],
    dataList: [],
  },
  showModal() {
    this.setData({
      modalName: "addgift"
    })
  },
  hideModal() {
    this.setData({
      modalName: '',
      files: [],
      gift: '',
      price: 0
    })
  },
  chooseImage() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.data.files.push(res.tempFilePaths[0])
        that.setData({
          files: that.data.files
        });
      },
    });
  },
  previewImage(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files, // 需要预览的图片http链接列表
    });
  },
  getgift(e) {
    this.setData({
      gift: e.detail.value
    })
  },
  getprice(e) {
    this.setData({
      price: parseInt(e.detail.value)
    })
  },
  convert(e) {
    if (this.data.score.score < this.data.dataList[e.target.dataset.index].price) {
      wx.showToast({
        icon: 'error',
        title: '积分不足',
      })
      return
    }
    this.data.score.score -= this.data.dataList[e.target.dataset.index].price
    wx.cloud.database().collection('score').doc(this.data.score._id).update({
      data: {
        score: this.data.score.score
      }
    }).then(res => {
      var DATE = utils.formatTime(new Date)
      wx.cloud.database().collection('record').add({
        data: {
          gift: this.data.dataList[e.target.dataset.index].gift,
          time: DATE
        }
      }).then(res => {
        wx.showToast({
          title: '兑换成功',
        })
        this.setData({
          score: this.data.score
        })
      })
    })
  },
  commit() {
    if (this.data.gift == '') {
      wx.showToast({
        icon: 'none',
        title: '礼物不能为空',
      })
      return
    } else if (isNaN(this.data.price) || this.data.price == 0) {
      wx.showToast({
        icon: 'none',
        title: '积分不能为空',
      })
      return
    } else if (this.data.files.length == 0) {
      wx.showToast({
        icon: 'none',
        title: '图片不能为空',
      })
      return
    }
    wx.showLoading({
      title: '上传中'
    })
    var path = Date.parse(new Date()) + this.data.files[0].substr(this.data.files[0].length - 10, 10)
    wx.cloud.uploadFile({
      cloudPath:  'image/' + path,
      filePath: this.data.files[0],
      success: res => {
        wx.cloud.database().collection('gift').add({
          data: {
            gift: this.data.gift,
            price: this.data.price,
            img: res.fileID,
            lover_openid: wx.getStorageSync('lover')._openid
          }
        }).then(() => {
          wx.hideLoading()
          wx.showToast({
            title: '提交成功',
          })
          this.hideModal()
          const db = wx.cloud.database()
          const _ = db.command
          var user = wx.getStorageSync('user')
          db.collection('gift').where(_.or([
            { _openid: user._openid },
            { lover_openid: user._openid }
          ])).get().then(res => {
            this.setData({
              dataList: res.data
            })
          })
        })
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.cloud.database().collection('score').where({
      _openid: wx.getStorageSync('user')._openid
    })
      .get()
      .then(res => {
        if (res.data.length == 0) {
          wx.cloud.database().collection('score').add({
            data: {
              score: parseInt(0)
            }
          }).then(res => {
            wx.cloud.database().collection('score').where({
              _openid: wx.getStorageSync('user')._openid
            }).get().then(res => {
              this.setData({
                score: res.data[0]
              })
            })
          })
        } else {
          wx.cloud.database().collection('score').where({
            _openid: wx.getStorageSync('user')._openid
          }).get().then(res => {
            this.setData({
              score: res.data[0]
            })
          })
        }
      })
    const db = wx.cloud.database()
    const _ = db.command
    var user = wx.getStorageSync('user')
    db.collection('gift').where(_.or([
      { _openid: user._openid },
      { lover_openid: user._openid }
    ])).get().then(res => {
      this.setData({
        dataList: res.data
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})